//
//  PartyDetailViewController.m
//  OneDay
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 oneDay. All rights reserved.
//

#import "PartyDetailViewController.h"
#import "DescriptionModel.h"
#import "PartyTextDetailTableViewCell.h"
#import "PartyImageTableViewCell.h"
#import "LoginViewController.h"
#import "PartyDetailModel.h"
#import "MapViewController.h"

@interface PartyDetailViewController ()<SDCycleScrollViewDelegate, MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) NSDictionary *locationDic;
@property (nonatomic, strong) SDCycleScrollView *sdScrollView;

@property (nonatomic, strong) NSMutableArray *desCriptionArray;
@property (nonatomic, strong) NSMutableArray *OneDayArray;

@property (nonatomic, strong) PartyDetailModel *partyDetailModel;

// 加载
@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;
@property (nonatomic, strong) NSString *headerStr;

@end

@implementation PartyDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.bounces = NO;
    
    [self addShareAndCollection];
    [self addIndicatorView];
    [self.indicatorView startAnimating];
    // 没有数据的时候为白色，没有线条
    self.tableView.separatorStyle = NO;
    NSString *partyUrl = [kPartyOne stringByAppendingString:[NSString stringWithFormat:@"%@",self.leo_id]];
    [self requestPartyDetailDataWithUrl:partyUrl block:^() {
        [self addCellHeaderAndFooter];
        self.headerStr = @"👉 OneDay提醒：";
        [self.tableView reloadData];
        [self.indicatorView stopAnimating];
    }];
    
    // 添加返回按钮
    UIBarButtonItem *leftB = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-reply-3.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBar:)];
    self.navigationItem.leftBarButtonItem = leftB;
}

// 添加返回按钮
- (void)backBar:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}

// 添加总的表头表尾
- (void)addCellHeaderAndFooter
{
    //  设置 总的(整个tableView的)表头表尾
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 540)];
    self.tableView.tableHeaderView = headerView;
    
    // 添加轮播图
    self.sdScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kWidth, 330) imageURLStringsGroup:self.partyDetailModel.images];
    // 几秒钟换图片
    self.sdScrollView.autoScrollTimeInterval = 4;
    // 小圆点的颜色
    self.sdScrollView.dotColor = [UIColor brownColor];
    // 小圆点的位置在中间还是右边
    self.sdScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    // 设置代理
    self.sdScrollView.delegate = self;
    [headerView addSubview:self.sdScrollView];
    
    // 添加标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.sdScrollView.bottom, kWidth, 50)];
    titleLabel.numberOfLines = 0;
    titleLabel.text = self.partyDetailModel.title;
    [headerView addSubview:titleLabel];
    
    // 添加类型和 价格
    UILabel *styleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, titleLabel.bottom, 80, 40)];
    NSString *str = self.partyDetailModel.category[@"cn_name"];
    styleLabel.text = str;
    [headerView addSubview:styleLabel];
    
    UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth - 130, titleLabel.bottom, 120, 40)];
    if ([self.partyDetailModel.price_info isEqualToString:@""]) {
        priceLabel.text = @"免费";
    }else if (self.partyDetailModel.price_info == nil){
        priceLabel.text = [NSString stringWithFormat:@"￥:%@", self.price_info];
    }else{
        priceLabel.text = [NSString stringWithFormat:@"￥:%@", self.partyDetailModel.price_info];
    }
    [headerView addSubview:priceLabel];
    
    UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, styleLabel.bottom, kWidth, 40)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    NSString *time_info = self.partyDetailModel.time[@"info"];
    if ([time_info isEqualToString:@""]) {
        timeLabel.text = @"随时可以来哦！！！";
    }else{
        timeLabel.text = time_info;
    }
    [headerView addSubview:timeLabel];
    
    // 添加地址
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(0, timeLabel.bottom, kWidth - 10, 50);
    NSString *addressStr = [self.partyDetailModel.address stringByAppendingString:self.partyDetailModel.poi];
    button.titleLabel.numberOfLines = 0;
    [button setTitle:addressStr forState:(UIControlStateNormal)];
    [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [button addTarget:self action:@selector(addressAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [headerView addSubview:button];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(button.right, button.frame.origin.y, 10, 50)];
    label.text = @">";
    [headerView addSubview:label];
    
    // 活动详情标题
    UILabel *description = [[UILabel alloc] initWithFrame:CGRectMake(0, button.bottom, kWidth, 30)];
    description.textAlignment = NSTextAlignmentCenter;
    description.text = @"——·活动详情·——";
    [headerView addSubview:description];
    
}
// 唯一的代理方法  选中图片执行
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    // 我的图片 -> MJPhoto
    
    NSMutableArray *phototArray = [NSMutableArray array];
    for (NSString *url in self.partyDetailModel.images) {
        MJPhoto *mjPhoto = [[MJPhoto alloc] init];
        mjPhoto.url = [NSURL URLWithString:url];
        [phototArray addObject:mjPhoto];
    }
    
    MJPhotoBrowser *brower = [[MJPhotoBrowser alloc] init];
    brower.photos = phototArray;
    brower.currentPhotoIndex = index;
    
    
    [brower show];
}
// address按钮点击方法
- (void)addressAction:(UIButton *)sender
{
    MapViewController *mapVC = [[MapViewController alloc] init];
    mapVC.locationDic = self.locationDic;
    [self.navigationController pushViewController:mapVC animated:YES];
    NSLog(@"%@", self.locationDic);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
       return self.desCriptionArray.count;
        
    }else{
        return self.OneDayArray.count;
        
    }
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 取消分割线
    self.tableView.separatorStyle = NO;
    if (indexPath.section == 0) {
        if (self.desCriptionArray.count > 0) {
            DescriptionModel *model = self.desCriptionArray[indexPath.row];
            if ([model.type isEqualToString:@"text"]) {
                PartyTextDetailTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                if (cell == nil) {
                    cell = [[PartyTextDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PartyTextDetailTableViewCell"];
                }
                cell.userInteractionEnabled = NO;
                cell.model = model;
                return cell;
            }else{
                PartyImageTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                if (cell == nil) {
                    cell = [[PartyImageTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PartyImageTableViewCell"];
                }
                cell.userInteractionEnabled = NO;
                cell.model = model;
                return cell;
            }
        }
    }else{
        if (self.OneDayArray.count > 0) {
            DescriptionModel *model = self.OneDayArray[indexPath.row];
            PartyTextDetailTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            if (cell == nil) {
                cell = [[PartyTextDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PartyTextDetailTableViewCell"];
            }
            cell.model = model;
            cell.userInteractionEnabled = NO;
            return cell;
        }
    }
    
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return self.headerStr;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OneDayObject *oneObject = [[OneDayObject alloc] init];
    if (indexPath.section == 0) {
        if (self.desCriptionArray.count > 0) {
            DescriptionModel *model = self.desCriptionArray[indexPath.row];
            if ([model.type isEqualToString:@"text"]) {
                return [oneObject sizeWithText:model.content font:16 width:kWidth - 20 height:10000].height;
            }else{
                NSArray *array = model.size;
                if (array.count > 0) {
                    CGFloat height = ([array[0] integerValue] / [array[1] integerValue]) * kWidth;
                    return height;
                }else{
                    return 250;
                }
            }
        }
    }else{
        if (self.OneDayArray.count > 0) {
            DescriptionModel *model = self.OneDayArray[indexPath.row];
            return [oneObject sizeWithText:model.content font:16 width:kWidth - 20 height:10000].height + 5;
        }
    }
    return 0;
}

#pragma mark -- 添加分享，收藏按钮
- (void)addShareAndCollection
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 0, kWidth - 70, 40)];
    NSArray *array = @[@"heart_shape_small_on", @"ic_nav_share_black"];
    for (int i = 0; i < 2; i++) {
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake(kWidth - 130 + i * 35, 7.5, 25, 25);
        [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [button setImage:[UIImage imageNamed:array[i]] forState:(UIControlStateNormal)];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        button.tag = i + 520;
        [view addSubview:button];
    }
    self.navigationItem.titleView  = view;
    
    
    // 创建返回左键
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItem:)];
    self.navigationItem.leftBarButtonItem = left;
}

// 分享收藏按钮方法
- (void)buttonAction:(UIButton *)sender
{
    if (sender.tag == 520) {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:nil message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        DataManager *manager = [DataManager shareManager];
        // 判断是否登录
        if ([manager isLogin] == NO) {
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            
            // 实现block
            loginVC.block = ^void(){
                NSLog(@"我已经成功");

            };
            
            UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:loginVC];
            [self presentViewController:navC animated:YES completion:nil];
        }else{
            LeanCloudObject *leanCloud = [[LeanCloudObject alloc] init];
            NSString *userName = [manager userName];
            NSLog(@"%@", userName);
            // 先判断是否收藏过
            NSArray *partyArray = [leanCloud selectStundetWithStyle:@"party" userName:userName];
            BOOL isHave = NO;
            for (PartyObject *party in partyArray) {
                if ([party.title isEqualToString:self.partyDetailModel.title]) {
                    isHave = YES;
                    break;
                }
            }
            if (isHave == NO) {
                // 取出图片数组第一张
                NSString *imageFirstUrl = self.partyDetailModel.images[0];
                [leanCloud creatObjectWithTitle:self.partyDetailModel.title imageUrl:imageFirstUrl needString:self.leo_id style:@"party" userName:userName];
                [alertView show];
            }else{
                alertView.message = @"您已经收藏过了";
                [alertView show];
            }
            // 实现 2 秒回收
            [self performSelector:@selector(actionAlert:) withObject:alertView afterDelay:2];
        }
        
    }else{
        // 拼接要分享的文字
        NSString *time_info = self.partyDetailModel.time[@"info"];
        NSString *addressStr = [self.partyDetailModel.address stringByAppendingString:self.partyDetailModel.poi];
        NSString *price;
        if ([self.partyDetailModel.price_info isEqualToString:@""]) {
            price = @"免费哦";
        }else{
            price = [NSString stringWithFormat:@"只要%@元哦", self.partyDetailModel.price_info];
        }
        // 图片
        UIImageView *imageView = [[UIImageView alloc] init];
        NSString *imageUrl = self.partyDetailModel.images[0];
        [imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:nil];
        // 需要分享的文字
        NSString *str = [NSString stringWithFormat:@"OneDay推荐：%@,时间：%@，地点：%@，%@",self.partyDetailModel.title, time_info, addressStr, price];
        
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"56396d0ee0f55aff4d0010a0"
                                          shareText:str
                                         shareImage:imageView.image
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent, UMShareToDouban,UMShareToEmail,UMShareToFacebook, nil]
                                           delegate:nil];
    }
}

#pragma mark -- 实现2秒消失
- (void)actionAlert:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];// 三秒回收
}


// 返回方法
- (void)leftBarButtonItem:(UIBarButtonItem *)buttonSender
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -- 数据请求
- (void)requestPartyDetailDataWithUrl:(NSString *)url block:(void (^)(void))block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [request setHTTPMethod:@"GET"];
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data == nil) {
                return;
            }
            
            NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *tempDic = rootDic[@"result"];
            PartyDetailModel *model = [[PartyDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            self.partyDetailModel = model;
            
            // description数组
            NSArray *descriptionArray = tempDic[@"description"];
            self.desCriptionArray = [NSMutableArray array];
            for (NSDictionary *dic1 in descriptionArray) {
                DescriptionModel *model = [[DescriptionModel alloc] init];
                [model setValuesForKeysWithDictionary:dic1];
                [self.desCriptionArray addObject:model];
            }
            // oneDay 提示数组
            NSArray *oneDayArray = tempDic[@"lrzm_tips"];
            self.OneDayArray = [NSMutableArray array];
            for (NSDictionary *dic2 in oneDayArray) {
                DescriptionModel *model = [[DescriptionModel alloc] init];
                [model setValuesForKeysWithDictionary:dic2];
                [self.OneDayArray addObject:model];
            }
            // 取出经纬度
            self.locationDic = tempDic[@"location"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }];
        [dataTask resume];
        
    });
}

#pragma mark - 添加加载等待动画
- (void)addIndicatorView
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.center = self.view.center;
    _indicatorView.delegate = self;
    
    _indicatorView.numberOfCircles = 5; // 圆点个数
    _indicatorView.internalSpacing = 5; // 圆点之间的距离
    _indicatorView.radius = 8; // 圆点半径
    //    _indicatorView.delay = 0;
    
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}

#pragma mark - 加载等待动画的代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
            return [UIColor redColor];
            break;
        case 1:
            return [UIColor magentaColor];
            break;
        case 2:
            return [UIColor orangeColor];
            break;
        case 3:
            return [UIColor purpleColor];
            break;
        default:
            return [UIColor yellowColor];
            break;;
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
